<?php
require('../../config/session.php');
$page_title = 'Search';
include('includes/header.html');

// Check if GET variables are preset.
$search_term_preset = " ";
$title_type_preset = " checked=\"true\" ";
$author_type_preset = " ";

if (!empty($_GET['search_term'])) {
    $search_term_preset = " value=\"" . $_GET['search_term'] . "\" ";
}
if (!empty($_GET['search_type'])) {
    if ($_GET['search_type'] == 'author') {
        $author_type_preset = $title_type_preset;
        $title_type_preset = " ";
    }
}

// Display an error message if search failed.
$search_error = false;

if (count($_GET) > 0) {
    if (empty($_GET['search_term'])) {
        echo "<p class=\"error\">Error: No search term was entered</p>\n";
        $search_error = true;
    } elseif (!($_GET['search_type'] == 'title' or $_GET['search_type'] == 'author')) {
        echo "<p class=\"error\">Error: Invalid search type</p>\n";
        $search_error = true;
    }
}
?>

<h1>Search for Books</h1>

<p>Enter a search by Name or Author.</p>

<br />

<form action="search.php" method="get">
    <p>Search term: <input type="text" name="search_term" size="45" maxlength="100"<?php echo $search_term_preset; ?>/></p>
    <p><input type="radio" name="search_type" value="title"<?php echo $title_type_preset; ?>/>By Title</p>
    <p><input type="radio" name="search_type" value="author"<?php echo $author_type_preset; ?>/>By Author</p>
    <p><input type="submit" value="Search" /></p>
</form>

<?php
require ('../../config/mysqli_connect.php'); // Connect to the db.

if (count($_GET) > 0 and !$search_error) {
    // If GET has any values, do a search
    echo "<br /><br />\n";

    $like_term = '%' . $_GET['search_term'] . '%';

    if ($_GET['search_type'] == 'title') {
        $stmt = $dbc->prepare("SELECT ISBN,Author,Title,Year FROM Books WHERE Title LIKE ?");
    } else {
        $stmt = $dbc->prepare("SELECT ISBN,Author,Title,Year FROM Books WHERE Author LIKE ?");
    }
    
    $stmt->bind_param("s", $like_term);
    $stmt->execute();

    $stmt->store_result();
    $stmt->bind_result($col1,$col2,$col3,$col4);

    echo "<table class=\"book-table\">\n";
    echo "<tr>\n";
    echo "<th style=\"width:200px\">Name</th>";
    echo "<th style=\"width:100px\">Author</th>";
    echo "<th style=\"width:50px\">Year</th>";
    echo "<th style=\"width:200px\">ISBN</th>";
    echo "</tr>\n";

    while ($stmt->fetch()) {
        echo "<tr>\n";
        echo "<td>" . $col3 . "</td>\n";
        echo "<td>" . $col2 . "</td>\n";
        echo "<td>" . $col4 . "</td>\n";
        echo "<td>" . $col1 . "</td>\n";
        echo "</tr>\n";
    }

    echo "</table>\n";
}

mysqli_close($dbc); // Close the database connection.
?>

<?php include ('includes/footer.html'); ?>
